/*
 * @lc app=leetcode.cn id=704 lang=java
 *
 * [704] 二分查找
 */

// @lc code=start
class Solution {
    public int search(int[] nums, int target) {
        if(target<nums[0]||target>nums[nums.length-1]){//首先考虑特殊情况进行优化
            return -1;
        }
        int left=0;
        int right=nums.length-1;
        while(left<=right){
            int middle=left+(right-left)/2;//避免（right+left）溢出
            if(target>nums[middle]){
                left=middle+1;
            }else if(target<nums[middle]){
                right=middle-1;
            }else{
                return middle;
            }
        }
        return -1;

    }
}
// @lc code=end

